<?php

class Assignments extends CActiveRecord {
/**
 * The followings are the available columns in table 'rbac_assignments':
 * @var string $itemname
 * @var integer $users_id
 * @var string $bizrule
 * @var string $data
 */

/**
 * Returns the static model of the specified AR class.
 * @return CActiveRecord the static model class
 */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'rbac_assignments';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
    // NOTE: you should only define rules for those attributes that
    // will receive user inputs.
        return array(
        array('itemname, userid, bizrule, data', 'required'),
        array('userid', 'numerical', 'integerOnly'=>true),
        array('itemname', 'length', 'max'=>50),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
    // NOTE: you may need to adjust the relation name and the related
    // class name for the relations automatically generated below.
        return array(
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
        'itemname' => Yii::t('crm', 'Name'),
        'userid' => Yii::t('crm', 'Nutzer'),
        'bizrule' => Yii::t('crm', 'Business - Logik'),
        'data' => Yii::t('crm', 'Daten'),
        );
    }

    public function assignAssignmentsByUserId($userId, array $values, $bizRules = null, $data = null) {
        foreach($values as $itemName) {
            $this->assignAssignmentByUserId($userId, $itemName, $bizRules, $data);
        }
        return true;
    }

    public function assignAssignmentByUserId($userId, $itemName, $bizRules = null, $data = null) {
        $assignment = new $this;
        $assignment->itemname = $itemName;
        $assignment->userid = $userId;
        $assignment->bizrule = $bizRules;
        $assignment->data = serialize($data);
        $assignment->insert();
        unset ($assignment);
    }

    public function revokeAssignmentsByUserId($userId, array $values) {
        foreach($values as $itemName) {
            if($itemName === Yii::app()->params['super_user']) {
                $auth = Yii::app()->authManager;
                $user_roles = $auth->getAuthItems(2,$userId);
                if(count($user_roles) < 2) {
                    return false;
                }
            }
            $this->revokeAssignmentByUserId($userId, $itemName);
        }
        return true;
    }

    public function revokeAssignmentByUserId($userId, $itemName) {
        $this->deleteAll('itemname=:itemname AND userid=:user_id', array(':itemname' => $itemName, ':user_id' => $userId));
    }

}